package com.ruoyi.system.service.aggregation.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.aggregation.ISmsService;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务实现类
 * 
 * @author ruoyi
 * @date 2025-01-01
 */
@Service
public class SmsServiceImpl implements ISmsService
{
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final int CODE_LENGTH = 6;
    private static final int CODE_EXPIRE_TIME = 5; // 5分钟过期

    /**
     * 发送短信验证码
     */
    @Override
    public boolean sendCode(String phone)
    {
        try
        {
            // 生成6位随机验证码
            String code = generateCode();
            
            // 存入Redis，5分钟过期
            String key = SMS_CODE_PREFIX + phone;
            redisTemplate.opsForValue().set(key, code, CODE_EXPIRE_TIME, TimeUnit.MINUTES);
            
            // TODO: 这里集成真实的短信服务（阿里云、腾讯云等）
            // 暂时只打印到控制台
            System.out.println("发送短信验证码到手机号：" + phone + "，验证码：" + code);
            
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证短信验证码
     */
    @Override
    public boolean verifyCode(String phone, String code)
    {
        String key = SMS_CODE_PREFIX + phone;
        String cachedCode = redisTemplate.opsForValue().get(key);
        
        if (cachedCode != null && cachedCode.equals(code))
        {
            // 验证成功后删除验证码
            redisTemplate.delete(key);
            return true;
        }
        
        return false;
    }

    /**
     * 生成随机验证码
     */
    private String generateCode()
    {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++)
        {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
}

